package com.platform.event.core.scheduler;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.w3c.dom.events.EventException;

import com.platform.event.core.EventService;
import com.platform.event.core.contants.EventConstants;
import com.platform.event.core.enums.EventStatusEnum;
import com.platform.event.core.model.BaseEvent;
import com.platform.task.core.DistributeTask;
import com.platform.task.core.impl.ThreadPoolTaskSchedulerComponent;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHander;
@JobHander(value="retryEventHandler")
@Service
public class SearchAndHandleWaitRetryEvent extends IJobHandler implements DistributeTask {

	Logger logger = LoggerFactory.getLogger(SearchAndHandleWaitRetryEvent.class);

	@Resource
	protected ThreadPoolTaskSchedulerComponent threadPoolTaskSchedulerComponent;

	@Resource
	private EventService eventService;

	@Override
	public String getTaskName() {
		// TODO Auto-generated method stub
		return SearchAndHandleWaitRetryEvent.class.getSimpleName();
	}

	@Override
	public void run() {
		List<BaseEvent> events = eventService.searchHandleEvent(EventStatusEnum.WAIT_RETRY.name());
		 logger.info("待处理事件数量: " + events.size());
		final CountDownLatch latch = new CountDownLatch(events.size());
		for (final BaseEvent event : events) {
			threadPoolTaskSchedulerComponent.getThreadPool(EventConstants.WAIT_RETRY_EVENT_TASK, 20)
					.execute(new Runnable() {
						@Override
						public void run() {
							try {
								eventService.handleEventProcess(event);
							} catch (EventException e) {
								logger.error(e.getMessage());
							} catch (Exception e) {
								logger.error(String.format("处理事件的时候发生异常, EventProcess[id=%d]", event.getId()), e);
							} finally {
								latch.countDown();
							}
						}

					});
		}
		try {
			// 等待事件异步处理完成
			latch.await(0, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			logger.error("", e);
		}
	}

	@Override
	public ReturnT<String> execute(String... params) throws Exception {
		run();
		return null;
	}

}
